package appapi.config.mongo;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;
@Configuration
public class MongoDBConfig {
    @Value("${spring.data.mongodb.uri}")
    private String mongoUri;
    @Value("${ssh.host}")
    private String sshHost;
    @Value("${ssh.port}")
    private int sshPort;
    @Value("${ssh.username}")
    private String sshUsername;
    @Value("${ssh.password}")
    private String sshPassword;
    @Bean
    public MongoDatabaseFactory mongoDatabaseFactory() throws JSchException {
        JSch jsch = new JSch();
        Session session = jsch.getSession(sshUsername, sshHost, sshPort);
        session.setPassword(sshPassword);
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();
        int assignedPort = session.setPortForwardingL(0, "localhost", 27017);
        String updatedUri = mongoUri.replace("localhost:27017", "localhost:" + assignedPort);
        return new SimpleMongoClientDatabaseFactory(updatedUri);
    }
    @Bean
    public MongoTemplate mongoTemplate(MongoDatabaseFactory mongoDatabaseFactory) {
        return new MongoTemplate(mongoDatabaseFactory);
    }
}